// pages/outvisit/task/uploadList.js
const innerAudioContext = wx.createInnerAudioContext();
var pagetitle = ["", "照片", "视频", "录音"];
var api = require("../../../utils/api.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    prePage: {},//上一个页面实例对象
    userId: 0,//用户ID
    outvisitTaskId: 0,//外访任务ID
    type: 0,//文件类型
    collectionCaseId: 0,//催收案件ID
    files: [],//文件列表
    photoFiles: [],//照片文件列表
    photoFilesMode: [
      { isMust: false, title: "评估委托书", files: [] },
      { isMust: false, title: "估价对象权属证明", files: [] },
      { isMust: false, title: "委托估价房地产法定优先受偿款承诺书", files: [] },
      { isMust: false, title: "身份证", files: [] },
      { isMust: false, title: "房地产证", files: [] },
    ],//照片文件列表模板
    videoSrc: "",//视频路径
    selectRecordIsHide: true,//选择录音是不是隐藏
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var pages = getCurrentPages();//获取页面栈
    var prePage = pages[pages.length - 2];//上一个页面实例对象
    var userId = wx.getStorageSync("userId");
    var outvisitTaskId = options.outvisitTaskId;
    var type = options.type;
    var collectionCaseId = options.collectionCaseId;
    // 设置标题
    wx.setNavigationBarTitle({
      title: "上传附件"
    });

    var filesList = that.getFiles(type);
    // 获取文件列表
    var files = filesList[0];
    // 获取照片文件列表
    var photoFiles = filesList[1];
    // 设置文件类型和文件列表
    that.setData({
      prePage: prePage,
      userId: userId,
      outvisitTaskId: outvisitTaskId,
      type: type,
      collectionCaseId: collectionCaseId,
      files: files,
      photoFiles: photoFiles,
    });
  },

  // 获取文件列表
  getFiles: function (type) {
    var that = this;
    var files = [];
    var photoFiles = [];
    var pages = getCurrentPages();//获取页面栈
    if (pages.length > 1) {
      //上一个页面实例对象
      var prePage = pages[pages.length - 2];
      if (type == 1) {
        // 获取照片文件列表
        photoFiles = that.getPhotoFiles(prePage.data.pictureFiles);
      }else if (type == 2) {
        files = prePage.data.videoFiles;
      } else if (type == 3) {
        files = prePage.data.recordFiles;
      }
    }
    return [files, photoFiles];
  },

  // 获取照片文件列表
  getPhotoFiles: function (files) {
    var that = this;
    var photoFiles = [
      { isMust: false, title: "评估委托书", files: [] },
      { isMust: false, title: "估价对象权属证明", files: [] },
      { isMust: false, title: "委托估价房地产法定优先受偿款承诺书", files: [] },
      { isMust: false, title: "身份证", files: [] },
      { isMust: false, title: "房地产证", files: [] },
    ];
    for (var i = 0; i < files.length; i++) {
      photoFiles[files[i].photoType - 1].files.push(files[i]);
    }
    return photoFiles;
  },

  // 选择文件
  selectFiles: function (e) {
    // 防止连续点击
    if (this.justClick) {
      return;
    }
    this.justClick = true;
    setTimeout(() => {
      this.justClick = false;
    }, 500);

    var photoType = e.currentTarget.dataset.photoType;//照片类型
    var type = this.data.type;
    if (type == 1) {
      // 选择图片
      if (this.data.photoFiles[photoType].files.length >= 12) { 
        wx.showToast({
          title: '已达图片最大上传数，请删除部分后再上传',
          icon: 'none'
        });
      } else {
        this.selectPicture(photoType);
      }
    } else if (type == 2) {
      // 选择视频
      if (this.data.files.length >= 6) {
        wx.showToast({
          title: '已达视频最大上传数，请删除部分后再上传',
          icon: 'none'
        });
      } else {
        this.selectVideo();
      }
    } else if (type == 3) {
      // 录音
      if (this.data.files.length >= 6) {
        wx.showToast({
          title: '已达录音最大上传数，请删除部分后再上传',
          icon: 'none'
        });
      } else {
        this.selectRecordShowOrHide();
      }
    }
  },

  // 选择录音方式
  selectRecord: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    this.selectRecordShowOrHide();
    if (type == 1) {
      wx.navigateTo({
        url: 'record?outvisitTaskId=' + this.data.outvisitTaskId + '&type=' + this.data.type + '&collectionCaseId=' + this.data.collectionCaseId
      });
    } else if (type == 2) {
      wx.navigateTo({
        url: 'selectRecord?collectionCaseId=' + this.data.collectionCaseId + '&type=' + this.data.type
      });
    }
  },

  // 选择图片
  selectPicture: function (photoType){
    var that = this;
    var photoType = photoType;
    
    wx.chooseMedia({
      count: 9, // 默认9,v2.25.0后最大到20
      mediaType: ['image'],
      sourceType: ['album', 'camera'],  // 可以拍摄或从相册中选择
      sizeType: ['original', 'compressed'],
      success: function (res) {
        // var tempFilePaths = res.tempFilePaths;
        var tempFilePaths = res.tempFiles;
        //启动上传等待中...
        wx.showLoading({
          title: "正在上传..."
        });
        // 文件数量，用于判断是否超过最大上传数
        var filesLength = that.data.photoFiles[photoType].files.length;
        var uploadCount = 0;
        var files = [];
        for (var i = 0, h = tempFilePaths.length; i < h && i + filesLength < 12; i++) {
          api.uploadFile(tempFilePaths[i].tempFilePath, that.data.collectionCaseId).then(res => {
            uploadCount++;
            var data = JSON.parse(res.data);
            if (data.code == 0) {
              files.push({
                filePath: data.data[0].filePath,
                fileType: that.data.type,
                photoType: parseInt(photoType) + 1
              });
            }
            // 保存图片
            that.savePicture(uploadCount, tempFilePaths.length, filesLength, files);
          }).catch(res => {
            uploadCount++;
            // 保存图片
            that.savePicture(uploadCount, tempFilePaths.length, filesLength, files);
          });
        }
      }
    });
  },

  // 保存图片
  savePicture: function (uploadCount, tempFilePathsLength, filesLength, files) {
    var that = this;
    //如果是最后一个,则保存
    if (uploadCount == tempFilePathsLength || uploadCount + filesLength >= 12) {
      if (files.length > 0) {
        that.formSubmit(files);
      } else {
        wx.hideLoading();
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        });
      }
    }
  },

  // 选择视频
  selectVideo:function(){
    var that = this;
    wx.chooseVideo({
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        //启动上传等待中...
        wx.showLoading({
          title: "正在上传..."
        });
        api.uploadFile(tempFilePath, that.data.collectionCaseId).then(res => {
          var data = JSON.parse(res.data);
          if (data.code == 0) {
            that.formSubmit([{
              filePath: data.data[0].filePath,
              fileType: that.data.type
            }]);
          } else {
            wx.hideLoading();
            wx.showToast({
              title: '上传失败',
              icon: 'none'
            });
          }
        }).catch(res => {
          wx.hideLoading();
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        });
      }
    });
  },

  // 合并录音
  mergeRecord: function () {
    var that = this;
    if (that.data.type == 3) {
      //启动上传等待中...
      wx.showLoading({
        title: "正在上传...",
        mask: true
      });
      var originalFilePath = wx.getStorageSync("originalFilePath-" + that.data.userId + "-" + that.data.outvisitTaskId);
      var tempsFile = wx.getStorageSync("tempsFile-" + that.data.userId + "-" + that.data.outvisitTaskId);
      if (originalFilePath && tempsFile) {
        api.mergeRecordFrame(that.data.collectionCaseId, originalFilePath, tempsFile).then(res => {
          if (res.code == 0) {
            var data = res.data;
            wx.removeStorageSync("originalFilePath-" + that.data.userId + "-" + that.data.outvisitTaskId);
            wx.removeStorageSync("tempsFile-" + that.data.userId + "-" + that.data.outvisitTaskId);
            that.formSubmit([{
              filePath: data[0].filePath,
              fileType: that.data.type
            }]);
          }
        });
      }
    }
  },

  // 提交表单
  formSubmit: function (file) {
    var that = this;
    //上一个页面实例对象
    var prePage = that.data.prePage;
    var submitData = prePage.data.outvistRecord;
    submitData.outvisitTaskId = prePage.data.id;
    var files = [].concat(prePage.data.pictureFiles, prePage.data.videoFiles, prePage.data.recordFiles, file);
    submitData.files = files;
    api.setOutvistRecord(submitData).then(res => {
      if (res.code == 0) {
        api.getOutvistRecord(prePage.data.id).then(res2 => {
          if (res2.code == 0) {
            wx.hideLoading();
            var data = res2.data;
            if (data) {
              // 设置外访记录id
              var outvistRecord = prePage.data.outvistRecord;
              outvistRecord.id = data.id;
              prePage.setData({
                outvistRecord: outvistRecord
              });
              // 设置文件列表
              var files2 = data.files;
              if (files2 && files2.length > 0) {
                // 设置文件列表
                var files3 = [];
                for (var i = 0; i < files2.length; i++) {
                  if (files2[i].fileType == that.data.type) {
                    files3.push(files2[i]);
                  }
                }
                // 获取文件列表
                var files4 = [];
                var photoFiles = [];
                if (that.data.type != 1) {
                  // 获取文件列表
                  files4 = files3;
                } else {
                  // 获取照片文件列表
                  photoFiles = that.getPhotoFiles(files3);
                }
                that.setData({
                  files: files4,
                  photoFiles: photoFiles
                }, () => {
                  // 提交数据
                  that.submitData();
                });
              }
            }
          }
        });
      }
    });
  },

  // 预览文件
  preview:function(e){
    var type = this.data.type;
    var photoType = e.currentTarget.dataset.photoType;//当前照片文件的类型
    var filePath = e.currentTarget.dataset.path;//当前文件的链接
    if (type == 1) {
      // 预览图片
      this.previewPicture(photoType, filePath);
    } else if (type == 2) {
      // 预览视频
      this.previewVideo(filePath);
    } else if (type == 3) {
      // 预览音频
      this.previewRecord(filePath);
    }
  },

  // 预览图片
  previewPicture: function (photoType, filePath) {
    // 获取图片链接列表
    var urls=[];//图片链接列表
    var files = this.data.photoFiles[photoType].files;
    for (var i = 0; i < files.length; i++) {
      urls.push(files[i].filePath);
    }
    // 开启图片预览
    wx.previewImage({
      current: filePath, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },

  // 预览视频
  previewVideo: function (filePath) {
    var videoContext = wx.createVideoContext("previewVideo",this);
    this.setData({
      videoSrc: filePath
    }, res => {
      videoContext.requestFullScreen({ direction: 0 });
    });
  },

  // 预览视频全屏切换事件
  previewVideoFullscreen:function(e){
    if (!e.detail.fullScreen){
      this.setData({
        videoSrc:""
      });
    }
  },

  // 预览音频
  previewRecord: function (filePath){
    innerAudioContext.src = filePath;
    innerAudioContext.play();
    innerAudioContext.onPlay(() => {
      wx.showToast({
        title: '开始播放',
        icon: 'none'
      });
    });
    innerAudioContext.onError(res => {
      wx.showToast({
        title: '播放失败',
        icon: 'none'
      });
    });
    innerAudioContext.onEnded(res => {
      wx.showToast({
        title: '播放结束',
        icon: 'none'
      });
    });
  },

  // 删除文件
  delFile:function(e){
    var that = this;
    wx.showModal({
      title: "提示",
      content: "确定删除吗？",
      success: function (sm) {
        console.log(e.currentTarget.dataset);
        var photoType = e.currentTarget.dataset.photoType;//当前照片文件的类型
        var index = e.currentTarget.dataset.index;//当前文件的下标
        var path = e.currentTarget.dataset.path;
        if (sm.confirm) {
          console.log("that.data.id====================>"+that.data.id);
          wx.showLoading({
            title: '删除中...',
          });
          api.deleteImage(that.data.id, photoType, that.data.floder, path).then(res => {
            if (res.code == 0) {
              wx.hideLoading();

              var filesList = that.getFiles(1);
              // 获取文件列表
              var files = filesList[1];
              // 获取照片文件列表
              var photoFiles = filesList[1];

              that.setData({
                files: files,
                photoFiles: photoFiles,
              });
            }
          });
        }
      }
    })
  },

  // 提交数据
  submitData:function(){
    var that = this;
    //上一个页面实例对象
    var prePage = that.data.prePage;
    var type = that.data.type;
    if (type == 1) {
      var photoFiles = that.data.photoFiles;
      var files = [];
      for (var i = 0; i < photoFiles.length; i++) {
        files = files.concat(photoFiles[i].files);
      }
      prePage.setData({
        pictureFiles: files
      });
    } else if (type == 2) {
      prePage.setData({
        videoFiles: that.data.files
      });
    } else if (type == 3) {
      prePage.setData({
        recordFiles: that.data.files
      });
    }
  },

  // 确定提交
  submit: function () {
    var that = this;
    // 提交数据
    that.submitData();
    // 返回
    wx.navigateBack({
      delta: 1,
    });
  },

  // 选择录音显示与隐藏
  selectRecordShowOrHide: function () {
    var selectRecordIsHide = this.data.selectRecordIsHide;
    if (selectRecordIsHide) {
      selectRecordIsHide = false;
    } else {
      selectRecordIsHide = true;
    }
    this.setData({
      selectRecordIsHide: selectRecordIsHide
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    innerAudioContext.stop();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    innerAudioContext.stop();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})